import os
import tempfile
import time
import traceback
import uuid

from aiohttp import web

from config import config
from event_handle.get_suggestion import get_suggestion, get_problem_detail
from event_handle.recall import get_recall_result, format_violation_detail
from file_manage.file import File
from file_valid.pipeline import FileValidPipeline
from knowledge_base.pipeline import KnowledgeBasePipeline
from emergency_plan.pipeline import EmergencyPlanPipeline
from emergency_plan.pdf_generator import EmergencyPlanPDFGenerator
from drill_script.pipeline import DrillScriptPipeline
from drill_script.save import DrillScriptSaver
from logger import logger
from util.common import context_format
from util.es import get_all_documents
from util.sse import SSEData

PORT = os.getenv("PORT", 8085)


def bad_request(code: int, msg: str):
    return web.json_response({"code": code, "msg": msg})


async def set_config(request):
    data = await request.json()
    if data:
        for k, v in data.items():
            config.set_config(k, v)
    return web.json_response({
        "code": 0,
        "msg": "ok"
    })


async def get_config(request):
    c = config.get_all_config()

    return web.json_response({
        "code": 0,
        "msg": "ok",
        "data": {"config": c}
    })


async def event_handler(request):
    if request.method == "GET":
        event_name = request.query.get("event_name", "")
        event_level = request.query.get("event_level", "")
        event_time = request.query.get("event_time", time.time())
        org_name = request.query.get("org_name", "")
        alarm_name = request.query.get("alarm_name", "")
        alarm_type = request.query.get("alarm_type", "")
        alarm_desc = request.query.get("alarm_desc", "")
        alarm_detail = request.query.get("alarm_detail", [])
    elif request.method == "POST":
        data = await request.json()
        event_name = data.get("event_name", "")
        event_level = data.get("event_level", "")
        event_time = data.get("event_time", 0)
        org_name = data.get("org_name", "")
        alarm_name = data.get("alarm_name", "")
        alarm_type = data.get("alarm_type", "")
        alarm_desc = data.get("alarm_desc", "")
        alarm_detail = data.get("alarm_detail", [])
        stream = data.get("stream", False)
    else:
        response = web.StreamResponse(
            status=405,
            reason='Method Not Allowed',
        )
        await response.prepare(request)
        await response.write("Method Not Allowed".encode('utf-8'))
        return response
    session_id = uuid.uuid4()
    logger.info(session_id,
                "参数： event_name: {}, event_level: {}, event_time: {}, org_name: {}, alarm_name: {}, alarm_type: {}, alarm_desc: {}, alarm_detail: {}".format(
                    event_name, event_level, event_time, org_name, alarm_name, alarm_type, alarm_desc,
                    alarm_detail))

    tags = ""
    if alarm_detail:
        for x in alarm_detail:
            org_name = x.get("org_name", org_name)
            alarm_name = x.get("alarm_name", alarm_name)
            alarm_type = x.get("alarm_type", alarm_type)
            alarm_desc = x.get("alarm_desc", alarm_desc)
            tags = x.get("tags", "")
    response = web.StreamResponse(
        status=200,
        reason='OK',
        headers={
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        })
    await response.prepare(request)
    try:
        violation_detail = await get_recall_result(
            event_name, event_level, event_time, org_name, alarm_name,
            alarm_type,
            alarm_desc
        )
        problem_detail = get_problem_detail(
            event_name, event_level, event_time, org_name, alarm_name,
            alarm_type,
            alarm_desc,
            violation_detail
        )
        suggestion = await get_suggestion(problem_detail, violation_detail, tags)
        alarm_detail_message = SSEData(problem_detail, "problem_detail")
        violation_detail = await format_violation_detail(violation_detail, problem_detail)
        violation_detail_message = SSEData(violation_detail, "violation_detail")
        await response.write(alarm_detail_message.data_pack())
        await response.write(violation_detail_message.data_pack())

        if suggestion:
            async for chunk in suggestion:
                print(chunk, end="")
                data = SSEData(chunk, "suggestion")
                await response.write(data.data_pack())

        await response.write(b"data: [DONE]\n\n")

    except Exception as e:
        print(traceback.format_exc())
        print("error: {}".format(e))

    finally:
        await response.write_eof()
        return response


async def knowledge_base_answer(request):
    if request.method == "GET":
        query = request.query.get("query", "")
        q_type = request.query.get("type", 1)
        permission_type = request.query.get("permission_type", 1)
        permission_set = request.query.get("permission_set", [])
        query_file = request.query.get("query_file", None)
        context = request.query.get("context", [])
    elif request.method == "POST":
        data = await request.json()
        query = data.get("query", "")
        q_type = data.get("type", 1)
        permission_type = data.get("permission_type", 1)
        permission_set = data.get("permission_set", [])
        query_file = data.get("query_file", None)
        context = data.get("context", [])
    else:
        response = web.StreamResponse(
            status=405,
            reason='Method Not Allowed',
        )
        await response.prepare(request)
        await response.write("Method Not Allowed".encode('utf-8'))
        return response
    session_id = uuid.uuid4()
    logger.info(session_id,
                "参数： query: {}, q_type: {}, permission_type: {}, permission_set: {}, query_file: {}, context: {}".format(
                    query, q_type, permission_type, permission_set, query_file, context))
    filter_files = []
    permission_list = permission_set
    if query_file is not None:
        filter_files = query_file
        permission_list = None
    else:
        try:
            permission_type = int(permission_type)
        except ValueError as e:
            return web.json_response({"code": 10001, "msg": "参数错误"})
        if permission_type != 1:
            permission_list = permission_set
        else:
            filter_files = None
            permission_list = None
    context = context_format(context)
    ppl = KnowledgeBasePipeline(query, context, filter_files, permission_list, q_type)

    response = web.StreamResponse(
        status=200,
        reason='OK',
        headers={
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        })
    await response.prepare(request)
    try:
        if not query:
            data = SSEData("请输入您的问题", "answer")
            await response.write(data.data_pack())
            await response.write(b"data: [DONE]\n\n")
        else:
            answer = await ppl.process(stream=True)
            print("知识库答案生成")
            if answer:
                async for chunk in answer:
                    print(chunk, end="")
                    data = SSEData(chunk, "answer")
                    await response.write(data.data_pack())
            await response.write(b"data: [DONE]\n\n")
    except Exception as e:
        print(traceback.format_exc())
        print("error: {}".format(e))
    finally:
        await response.write_eof()
        return response


async def knowledge_base_upload(request):
    global temp_path
    reader = await request.multipart()

    # 初始化变量
    op_type = 1
    file = None
    file_name = ""
    file_id = ""
    permission_type = 1
    permission_set = []
    # 读取所有字段
    while True:
        field = await reader.next()
        if not field:
            break

        # 获取用户名
        if field.name == 'op_type':
            op_type = await field.text()
            if not op_type:
                return bad_request(10001, "参数错误")
        # 获取文件
        elif field.name == 'file':
            file = field
            if not file and op_type == 1:
                return bad_request(10001, "参数错误")
            file_field = field
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.tmp')
            temp_path = temp_file.name

            while True:
                chunk = await file_field.read_chunk()
                if not chunk:
                    break
                temp_file.write(chunk)
            temp_file.close()
        elif field.name == 'file_name':
            file_name = await field.text()
        elif field.name == 'file_id':
            file_id = await field.text()
            if not file_id:
                return bad_request(10001, "参数错误")
        elif field.name == 'permission_type':
            permission_type = await field.text()
        elif field.name == 'permission_set':
            permission_set = await field.text()
    if not (file_id and op_type):
        return bad_request(10001, "参数错误")
    if not permission_type:
        permission_type = 1
    if not permission_set:
        permission_set = []
    session_id = uuid.uuid4()
    logger.info(session_id,
                "参数： op_type: {}, file_name: {}, file_id: {}, permission_type: {}, permission_set: {}".format(
                    op_type,
                    file_name,
                    file_id,
                    permission_type,
                    permission_set))
    file_obj = File(
        file=b'',
        file_name=file_name,
        file_id=file_id,
        permission_set=permission_set,
        permission_type=permission_type,
        file_path=temp_path
    )
    if op_type == 2:
        file_obj.delete_from_es()
    else:
        file_type = file_obj.detect_file_type()
        print(file_type)
        if not file_type:
            return web.json_response({
                "code": 10002,
                "msg": "不支持的文件格式",
            })
        file_obj.file_save()
        await file_obj.file_extract(file_type)
        file_obj.content_trunk()
        await file_obj.upload_to_es()

    return web.json_response({
        "code": 0,
        "msg": "操作成功",
    })


async def document_compliance(request):
    # 解析表单数据
    global temp_path
    reader = await request.multipart()

    # 初始化参数
    file_id = None
    permission_set = None
    permission_type = None
    query_file = None
    file_field = None

    # 遍历所有字段
    while True:
        field = await reader.next()
        if field is None:
            break
        if field.name == 'file_id':
            file_id = await field.text()
        if field.name == 'permission_set':
            permission_set = await field.text()
        elif field.name == 'permission_type':
            permission_type = await field.text()
        elif field.name == 'query_file':
            query_file = await field.text()
        elif field.name == 'file':
            file_field = field
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.tmp')
            temp_path = temp_file.name

            while True:
                chunk = await file_field.read_chunk()
                if not chunk:
                    break
                temp_file.write(chunk)
            temp_file.close()

    # 验证必填参数
    if not file_field:
        return bad_request(10001, "参数错误")

    file_obj = File(
        file=b"",
        file_name="",
        file_id=file_id,
        permission_set=permission_set,
        permission_type=permission_type,
        file_path=temp_path
    )
    file_obj.file_save()
    file_type = file_obj.detect_file_type()
    if not file_type:
        return bad_request(10002, "不支持的文件格式")
    await file_obj.file_extract(file_type)
    file_obj.content_trunk(overlap=100)

    response = web.StreamResponse(
        status=200,
        reason='OK',
        headers={
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        })
    await response.prepare(request)
    try:
        ppl = FileValidPipeline(file_obj.trunks)
        answer = ppl.process()
        data = SSEData("正在分析：\n", "answer")
        await response.write(data.data_pack())
        if answer:
            async for chunk in answer:
                print(chunk, end="")
                data = SSEData(chunk, "answer")
                await response.write(data.data_pack())
        await response.write(b"data: [DONE]\n\n")
    except Exception as e:
        traceback.print_exc()
        print("error: {}".format(e))

    finally:
        await response.write_eof()
        return response


async def get_documents_list(request):
    """获取所有上传的文档列表"""
    try:
        documents = get_all_documents()
        return web.json_response({
            "code": 0,
            "msg": "获取成功",
            "data": documents
        })
    except Exception as e:
        logger.error(f"获取文档列表失败: {e}")
        return web.json_response({
            "code": 1,
            "msg": f"获取文档列表失败: {str(e)}",
            "data": []
        }, status=500)


async def generate_emergency_plan(request):
    """应急预案生成接口"""
    try:
        data = await request.json()
        
        # 获取参数
        event_type = data.get("event_type", "")
        event_subtype = data.get("event_subtype", "")
        optimize_field = data.get("optimize_field", "")
        optimize_suggest = data.get("optimize_suggest", "")
        history = data.get("history", [])
        
        # 参数验证
        if not event_type or not event_subtype:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：event_type和event_subtype为必填项",
                "plan": []
            })
        
        # 验证优化参数
        if optimize_field and not history:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：optimize_field有值时history也必须提供",
                "plan": []
            })
        
        session_id = uuid.uuid4()
        logger.info(session_id,
                    "应急预案生成参数： event_type: {}, event_subtype: {}, optimize_field: {}, optimize_suggest: {}, history_length: {}".format(
                        event_type, event_subtype, optimize_field, optimize_suggest, len(history) if history else 0))
        
        # 创建应急预案生成pipeline
        pipeline = EmergencyPlanPipeline(
            event_type=event_type,
            event_subtype=event_subtype,
            optimize_field=optimize_field if optimize_field else None,
            optimize_suggest=optimize_suggest if optimize_suggest else None,
            history=history if history is not None else [],
            retrieval_only=True  # 切换到纯检索模式
        )
        
        # 生成应急预案
        result = await pipeline.process()
        
        # 返回结果
        if isinstance(result, dict) and result.get("mode") == "retrieval_only":
            # 纯检索模式：返回检索到的文档
            return web.json_response({
                "status_code": 0,
                "message": "检索完成，返回相关文档",
                "plan": result.get("data", {})
            })
        else:
            # RAG模式：返回生成的预案
            return web.json_response({
                "status_code": 0,
                "message": "正常",
                "plan": result
            })
        
    except Exception as e:
        logger.error(f"应急预案生成失败: {e}")
        print(traceback.format_exc())
        return web.json_response({
            "status_code": 20001,
            "message": f"服务器内部错误: {str(e)}",
            "plan": []
        }, status=500)


async def save_emergency_plan(request):
    """保存应急预案到知识库接口"""
    try:
        data = await request.json()
        
        # 获取参数
        event_type = data.get("event_type", "")
        event_subtype = data.get("event_subtype", "")
        plan = data.get("plan", [])
        
        # 参数验证
        if not event_type or not event_subtype:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：event_type和event_subtype为必填项"
            })
        
        if not plan or not isinstance(plan, list):
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：plan必须是非空数组"
            })
        
        # 验证预案字段
        required_fields = [
            "安全事件监测",
            "安全事件分析、定级、上报", 
            "应急响应处置",
            "安全事件取证和溯源",
            "安全事件总结、结束响应"
        ]
        
        plan_fields = [item.get("field_name", "") for item in plan] if plan else []
        missing_fields = [field for field in required_fields if field not in plan_fields]
        
        if missing_fields:
            return web.json_response({
                "status_code": 10001,
                "message": f"参数错误：预案缺少必要字段: {', '.join(missing_fields)}"
            })
        
        session_id = uuid.uuid4()
        logger.info(session_id,
                    "保存应急预案参数： event_type: {}, event_subtype: {}, plan_fields: {}".format(
                        event_type, event_subtype, plan_fields))
        
        # 生成PDF文件
        pdf_generator = EmergencyPlanPDFGenerator()
        pdf_bytes = pdf_generator.generate_pdf_bytes(event_type, event_subtype, plan)
        
        # 生成文件ID和文件名
        file_id = f"emergency_plan_{event_type}_{event_subtype}_{int(time.time())}"
        file_name = f"{event_type}-{event_subtype}应急预案.pdf"
        
        # 创建File对象
        file_obj = File(
            file_id=file_id,
            file_name=file_name,
            permission_type=1,
            permission_set=[],  # 默认所有人可访问
            file=pdf_bytes,
            file_path=None  # 使用字节数据而不是文件路径
        )
        
        # 检测文件类型
        file_type = file_obj.detect_file_type()
        if not file_type:
            return web.json_response({
                "status_code": 10002,
                "message": "文件类型检测失败"
            })
        
        # 保存文件并提取内容
        file_obj.file_save()
        await file_obj.file_extract(file_type, use_simple_extract=True)  # 使用简化的PDF提取
        file_obj.content_trunk()
        
        # 上传到Elasticsearch
        await file_obj.upload_to_es()
        
        return web.json_response({
            "status_code": 0,
            "message": "应急预案保存成功",
            "data": {
                "file_id": file_id,
                "file_name": file_name
            }
        })
        
    except Exception as e:
        logger.info(uuid.uuid4(), f"保存应急预案失败: {e}")
        print(f"保存应急预案失败: {e}")
        print(traceback.format_exc())
        return web.json_response({
            "status_code": 20001,
            "message": f"服务器内部错误: {str(e)}"
        }, status=500)


async def generate_drill_script_api(request):
    """演练脚本生成接口"""
    # 记录API开始时间
    api_start_time = time.time()
    
    try:
        # 记录请求解析开始时间
        parse_start_time = time.time()
        
        data = await request.json()
        
        # 获取参数
        equipment = data.get("equipment", "")
        scene_desc = data.get("sceneDesc", "")
        plan = data.get("plan", {})
        script_node = data.get("scriptNode", [])
        
        parse_end_time = time.time()
        parse_duration = parse_end_time - parse_start_time
        print(f"⏱️ 请求解析耗时: {parse_duration:.3f}秒")
        
        # 记录参数验证开始时间
        validation_start_time = time.time()
        
        # 参数验证
        if not equipment:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：equipment为必填项"
            })
        
        if not scene_desc:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：sceneDesc为必填项"
            })
        
        if not plan or not isinstance(plan, dict):
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：plan必须是非空字典"
            })
        
        if not script_node or not isinstance(script_node, list):
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：scriptNode必须是非空数组"
            })
        
        validation_end_time = time.time()
        validation_duration = validation_end_time - validation_start_time
        print(f"⏱️ API参数验证耗时: {validation_duration:.3f}秒")
        
        session_id = uuid.uuid4()
        logger.info(session_id,
                    "演练脚本生成参数： equipment: {}, scene_desc: {}, plan_fields: {}, script_node_count: {}".format(
                        equipment, scene_desc, list(plan.keys()), len(script_node) if script_node else 0))
        
        # 记录pipeline创建开始时间
        pipeline_create_start_time = time.time()
        
        # 创建演练脚本生成pipeline
        pipeline = DrillScriptPipeline(
            equipment=equipment,
            scene_desc=scene_desc,
            plan=plan,
            script_node=script_node,
            retrieval_only=True  # 切换到纯检索模式
        )
        
        pipeline_create_end_time = time.time()
        pipeline_create_duration = pipeline_create_end_time - pipeline_create_start_time
        print(f"⏱️ Pipeline创建耗时: {pipeline_create_duration:.3f}秒")
        
        # 记录脚本生成开始时间
        generation_start_time = time.time()
        
        # 生成演练脚本
        result = await pipeline.process()
        
        generation_end_time = time.time()
        generation_duration = generation_end_time - generation_start_time
        print(f"⏱️ 脚本生成耗时: {generation_duration:.3f}秒")
        
        # 记录API结束时间
        api_end_time = time.time()
        api_duration = api_end_time - api_start_time
        
        print(f"⏱️ API总体耗时: {api_duration:.3f}秒")
        print(f"📊 API耗时分析:")
        print(f"   - 请求解析: {parse_duration:.3f}秒 ({(parse_duration/api_duration)*100:.1f}%)")
        print(f"   - 参数验证: {validation_duration:.3f}秒 ({(validation_duration/api_duration)*100:.1f}%)")
        print(f"   - Pipeline创建: {pipeline_create_duration:.3f}秒 ({(pipeline_create_duration/api_duration)*100:.1f}%)")
        print(f"   - 脚本生成: {generation_duration:.3f}秒 ({(generation_duration/api_duration)*100:.1f}%)")
        
        # 返回结果 - 统一处理两种模式
        if isinstance(result, dict) and "scriptNode" in result:
            # 两种模式都返回scriptNode，保持结构一致
            response_data = {
                "status_code": 0,
                "message": "正常",
                "scriptNode": result.get("scriptNode", [])
            }
            
            # 如果是纯检索模式，添加相关文档信息
            if "related_documents" in result:
                response_data["related_documents"] = result.get("related_documents", [])
                response_data["message"] = "检索完成，返回相关演练脚本文档"
            
            return web.json_response(response_data)
        else:
            # 异常情况
            return web.json_response({
                "status_code": 20001,
                "message": "返回结果格式错误"
            }, status=500)
        
    except Exception as e:
        logger.error(f"演练脚本生成失败: {e}")
        print(traceback.format_exc())
        return web.json_response({
            "status_code": 20001,
            "message": f"服务器内部错误: {str(e)}"
        }, status=500)


async def save_drill_script_api(request):
    """演练脚本保存接口"""
    # 记录API开始时间
    save_api_start_time = time.time()
    
    try:
        # 记录请求解析开始时间
        save_parse_start_time = time.time()
        
        data = await request.json()
        
        # 获取参数
        equipment = data.get("equipment", "")
        scene_desc = data.get("sceneDesc", "")
        plan = data.get("plan", {})
        script_node = data.get("scriptNode", [])
        
        save_parse_end_time = time.time()
        save_parse_duration = save_parse_end_time - save_parse_start_time
        print(f"⏱️ 保存请求解析耗时: {save_parse_duration:.3f}秒")
        
        # 记录参数验证开始时间
        save_validation_start_time = time.time()
        
        # 参数验证
        if not equipment:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：equipment为必填项"
            })
        
        if not scene_desc:
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：sceneDesc为必填项"
            })
        
        if not plan or not isinstance(plan, dict):
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：plan必须是非空字典"
            })
        
        if not script_node or not isinstance(script_node, list):
            return web.json_response({
                "status_code": 10001,
                "message": "参数错误：scriptNode必须是非空数组"
            })
        
        save_validation_end_time = time.time()
        save_validation_duration = save_validation_end_time - save_validation_start_time
        print(f"⏱️ 保存参数验证耗时: {save_validation_duration:.3f}秒")
        
        session_id = uuid.uuid4()
        logger.info(session_id,
                    "保存演练脚本参数： equipment: {}, scene_desc: {}, plan_fields: {}, script_node_count: {}".format(
                        equipment, scene_desc, list(plan.keys()), len(script_node) if script_node else 0))
        
        # 记录保存器创建开始时间
        saver_create_start_time = time.time()
        
        # 创建演练脚本保存器
        saver = DrillScriptSaver(
            equipment=equipment,
            scene_desc=scene_desc,
            plan=plan,
            script_node=script_node
        )
        
        saver_create_end_time = time.time()
        saver_create_duration = saver_create_end_time - saver_create_start_time
        print(f"⏱️ 保存器创建耗时: {saver_create_duration:.3f}秒")
        
        # 记录保存操作开始时间
        save_operation_start_time = time.time()
        
        # 保存脚本到知识库
        result = await saver.save_to_knowledge_base()
        
        save_operation_end_time = time.time()
        save_operation_duration = save_operation_end_time - save_operation_start_time
        print(f"⏱️ 保存操作耗时: {save_operation_duration:.3f}秒")
        
        # 记录API结束时间
        save_api_end_time = time.time()
        save_api_duration = save_api_end_time - save_api_start_time
        
        print(f"⏱️ 保存API总体耗时: {save_api_duration:.3f}秒")
        print(f"📊 保存API耗时分析:")
        print(f"   - 请求解析: {save_parse_duration:.3f}秒 ({(save_parse_duration/save_api_duration)*100:.1f}%)")
        print(f"   - 参数验证: {save_validation_duration:.3f}秒 ({(save_validation_duration/save_api_duration)*100:.1f}%)")
        print(f"   - 保存器创建: {saver_create_duration:.3f}秒 ({(saver_create_duration/save_api_duration)*100:.1f}%)")
        print(f"   - 保存操作: {save_operation_duration:.3f}秒 ({(save_operation_duration/save_api_duration)*100:.1f}%)")
        
        # 返回结果
        return web.json_response({
            "status_code": 0,
            "message": "演练脚本保存成功",
            "data": result
        })
        
    except Exception as e:
        logger.error(f"演练脚本保存失败: {e}")
        print(traceback.format_exc())
        return web.json_response({
            "status_code": 20001,
            "message": f"服务器内部错误: {str(e)}"
        }, status=500)


async def health_check(request):
    """健康检查端点"""
    return web.json_response({
        "status": "healthy",
        "timestamp": time.time(),
        "service": "security-warning"
    })


app = web.Application()
app.router.add_get('/health', health_check)
app.router.add_post('/event_handle', event_handler)
app.router.add_get('/event_handle', event_handler)
app.router.add_post('/knowledge_base/answer', knowledge_base_answer)
app.router.add_get('/knowledge_base/answer', knowledge_base_answer)
app.router.add_post('/knowledge_base/upload', knowledge_base_upload)
app.router.add_get('/knowledge_base/documents', get_documents_list)
# app.router.add_post('/config/set', set_config)
# app.router.add_get('/config/get', get_config)
app.router.add_post('/knowledge_base/document_compliance', document_compliance)
app.router.add_post('/api/v1/generate_plan', generate_emergency_plan)
app.router.add_post('/api/v1/save_plan', save_emergency_plan)
app.router.add_post('/api/v1/generate_drill_script', generate_drill_script_api)
app.router.add_post('/api/v1/save_script', save_drill_script_api)

app.router.add_static('/', path='./', show_index=False)

if __name__ == '__main__':
    web.run_app(app, port=PORT)
